﻿using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using WebApi0001.Controllers;
using WebApi0001.Interface;
using WebApplication1.Domain;

namespace WebApi0001.Implementation
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity//实现接口
    {
        private readonly Admin1000DbContext db;

        private DbSet<T> _entity;

        protected DbSet<T> Entity
        {
            get
            {

                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }

                return _entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public EfRespository(Admin1000DbContext dbContext)
        {
            db = dbContext;
        }


        public void Delete(T entity)
        {
            this._entity.Remove(entity);

            db.SaveChanges();//保存修改
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.id == id).FirstOrDefault();
            //调用上面的函数
            Delete(row);
        }

        //public IEnumerable<T> GetAllEntity()
        //{
        //    throw new NotImplementedException();
        //}

        public T GetById(int id)
        {
            return _entity.Where(x => x.id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}